<template>
  <n-breadcrumb class="px-12px">
    <template v-for="breadcrumb in breadcrumbs" :key="breadcrumb.key">
      <n-breadcrumb-item>
        <n-dropdown
          v-if="breadcrumb.hasChildren"
          :options="breadcrumb.options"
          @select="dropdownSelect"
        >
          <div flex-y-center>
            <component :is="breadcrumb.icon!" />
            <span ml-3 line-height-14>
              {{ breadcrumb.label }}
            </span>
          </div>
        </n-dropdown>
        <div v-else flex-y-center>
          <component :is="breadcrumb.icon!" />
          <span ml-3 line-height-14>{{ breadcrumb.label }}</span>
        </div>
      </n-breadcrumb-item>
    </template>
  </n-breadcrumb>
</template>

<script setup lang="ts">
import { useRouterStore } from "@/store";
import { type DropdownOption } from "naive-ui";

const route = useRoute();
const router = useRouter();
const routerStore = useRouterStore();

console.log(route.matched);

const breadcrumbs = computed(() => {
  let breadcrumbs = [];
  const tmpMenus = ref(routerStore.menus);
  for (const idx in route.matched) {
    const routeMch = route.matched[idx];
    let menuMapper = tmpMenus.value!.find((menu) => menu.key == routeMch.name);
    // @ts-ignore
    tmpMenus.value = menuMapper!.children;
    let options = menu2Dropdown(
      menuMapper!.children,
      route.matched[Number(idx) + 1]?.name as string
    );
    breadcrumbs.push({
      options,
      hasChildren: !!options && !!options.length,
      icon: menuMapper!.icon,
      label: menuMapper!.label,
    });
  }
  return breadcrumbs;
});

const menu2Dropdown = (
  menus?: Sys.Menu[],
  nextKey?: string
): DropdownOption[] | undefined => {
  if (!menus || !menus.length) return;

  return menus
    .filter((menu) => !nextKey || menu.key != nextKey)
    .map((menu) => {
      return {
        label: menu.label as string,
        key: menu.key as string,
        icon: menu.icon,
        children: menu2Dropdown(menu.children),
      };
    });
};

const dropdownSelect = (key: string) => {
  router.push({ name: key });
};
</script>

<style scoped></style>
